package org.example.redisson;

import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Classname RedisLockImpl
 * @Description 封装redis分布锁加锁解锁
 * @Date 2021/3/24 4:16 下午
 * 可重入性
 * @Created by xiangjd
 */
public class RedisLockImpl1 implements RedisLock {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //把加锁和解锁放在同一个线程里,防止不同线程之间串改
    private ThreadLocal<String> threadLocal = new ThreadLocal<String>();

    @Override
    public boolean tryLock(String key, long timeout, TimeUnit unit) {
        boolean isLock = false;
        if (threadLocal.get() == null) {
            String uuid = UUID.randomUUID().toString();
            threadLocal.set(uuid);
            isLock = stringRedisTemplate.opsForValue().setIfAbsent(key, uuid, timeout, unit);
        } else {
            isLock = true;
        }
        return isLock;
    }

    @Override
    public void releaseLock(String key) {
        //当前线程的uuid和redis中的uuid一样才能进行删除
        if (threadLocal.get().equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }
}
